<?php

declare (strict_types=1);

namespace app\admin\model\admin;

use app\common\model\admin\UserRole as UserRoleModel;
use Exception;

/**
 * 管理用户角色模型
 * Class UserRole
 * @package app\admin\model\admin
 */
class UserRole extends UserRoleModel
{
    /**
     * 新增关系记录
     * @param int $adminUserId
     * @param array $roleIds
     * @return array|false
     */
    public static function increased(int $adminUserId, array $roleIds)
    {
        $data = [];
        foreach ($roleIds as $roleId) {
            $data[] = [
                'admin_user_id' => $adminUserId,
                'role_id' => $roleId,
            ];
        }
        return (new static)->addAll($data);
    }

    /**
     * 更新关系记录
     * @param int $adminUserId
     * @param array $newRoles 新的角色集
     * @return array|false
     * @throws Exception
     */
    public static function updates(int $adminUserId, array $newRoles)
    {
        // 已分配的角色集
        $assignRoleIds = self::getRoleIdsByUserId($adminUserId);
        // 找出删除的角色
        $deleteRoleIds = array_diff($assignRoleIds, $newRoles);
        if (!empty($deleteRoleIds)) {
            self::deleteAll([
                ['admin_user_id', '=', $adminUserId],
                ['role_id', 'in', $deleteRoleIds]
            ]);
        }
        // 找出添加的角色
        $newRoleIds = array_diff($newRoles, $assignRoleIds);
        $data = [];
        foreach ($newRoleIds as $roleId) {
            $data[] = [
                'admin_user_id' => $adminUserId,
                'role_id' => $roleId,
            ];
        }
        return (new static)->addAll($data);
    }

    /**
     * 获取指定管理员的所有角色id
     * @param int $adminUserId
     * @return array
     */
    public static function getRoleIdsByUserId(int $adminUserId)
    {
        return (new static)->where('admin_user_id', '=', $adminUserId)->column('role_id');
    }

    /**
     * 根据角色ID判断是否存在用户
     * @param int $roleId
     * @return bool
     */
    public static function isExistsUserByRoleId(int $roleId)
    {
        return !!(new static)->where('role_id', '=', $roleId)->count();
    }
}
